﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Xml;
using EmoneyWeiXinBLL;
using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using EmoneyWeiXinThreadBLL;
using EmoneyWeiXinThreadDAL;
using System.Threading;

namespace EmoneyWeiXin.Controllers
{


    public class WXOpenController : Controller
    {
        //
        // GET: /WXOpen/

        public string result = "";
        public string weixinid = "";
        public int Newsreportid = 0;
        public string stock = "";
        public int isstock = 0; //是否是股票代码
        public int utype = 1;
        public int baseZanNum = 18;//基础赞的数量
        public static object lockObject = new object();
        /// <summary>
        /// 备用，keyWord（关键字） ClickMenu（点击栏目菜单） CommonContent（普通内容） subscribe（关注）unsubscribe（取消关注）
        /// </summary>
        public enum MyMsgType
        {
            CommonContent = 1, keyWord = 8, ClickMenu = 3, ClickMenuUrl = 4, unsubscribe = 5, subscribe = 6, SCAN = 7
        }
        public ActionResult Index2()
        {
            weixinid = "12";
            // return Content(getKeyWordGPFC("", "", "大秦铁路", ""));
            string json = GetKeyCodeReply("", "", "518");
            // return Content(GetKeyCodeReply("otfN4s4QyNwq9wSHc9OiA_4U_pw4", "otfN4s4QyNwq9wSHc9OiA_4U_pw4", "999"));
            //  GetXml3("", "", "", "jpzx");
            return null;
        }

        public ActionResult Index()
        {
            string postStr = "";
            weixinid = string.IsNullOrEmpty(Request.QueryString["weixinid"]) ? "8" : Request.QueryString["weixinid"];
            RequestXML requestXML = new RequestXML();
            //StockDoctorPhoneLogBLL.SetStockDoctorPhoneLog(new StockDoctorlogEntity(weixinid, Newsreportid, requestXML.FromUserName, 1, requestXML.ToUserName, requestXML.Content, requestXML.EventKey, stock, result, System.DateTime.Now, requestXML.PicUrl, isstock));
            if (Request.HttpMethod.ToLower() == "post")
            {
                using (Stream stream = System.Web.HttpContext.Current.Request.InputStream)
                {
                    byte[] b = new byte[stream.Length];
                    stream.Read(b, 0, (int)stream.Length);
                    postStr = Encoding.UTF8.GetString(b);

                    if (!string.IsNullOrEmpty(postStr))
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml(postStr);
                        XmlElement rootElement = doc.DocumentElement;
                        XmlNode MsgType = rootElement.SelectSingleNode("MsgType");
                        requestXML.ToUserName = rootElement.SelectSingleNode("ToUserName").InnerText;
                        requestXML.FromUserName = rootElement.SelectSingleNode("FromUserName").InnerText;
                        requestXML.CreateTime = rootElement.SelectSingleNode("CreateTime").InnerText;
                        requestXML.MsgType = MsgType.InnerText;

                        if (requestXML.MsgType == "text")
                        {
                            requestXML.Content = rootElement.SelectSingleNode("Content").InnerText;
                        }
                        else if (requestXML.MsgType == "location")
                        {
                            requestXML.Location_X = rootElement.SelectSingleNode("Location_X").InnerText;
                            requestXML.Location_Y = rootElement.SelectSingleNode("Location_Y").InnerText;
                            requestXML.Scale = rootElement.SelectSingleNode("Scale").InnerText;
                            requestXML.Label = rootElement.SelectSingleNode("Label").InnerText;
                        }
                        else if (requestXML.MsgType == "image")
                        {
                            requestXML.PicUrl = rootElement.SelectSingleNode("PicUrl").InnerText;
                        }
                        else if (requestXML.MsgType == "event")
                        {
                            requestXML.Event = rootElement.SelectSingleNode("Event").InnerText;
                            requestXML.EventKey = rootElement.SelectSingleNode("EventKey").InnerText;
                            try
                            {
                                requestXML.Ticket = rootElement.SelectSingleNode("Ticket").InnerText;
                            }
                            catch (Exception)
                            {

                            }
                        }

                        result = ResponseMsg(requestXML);

                    }
                }
            }
            else
            {
                result = Valid();
            }

            if (requestXML.MsgType == "event")
            {
                if (requestXML.Event == "subscribe" || requestXML.Event == "unsubscribe" || requestXML.Event == "SCAN")
                {
                    if (requestXML.Event == "subscribe")
                    {
                        utype = 6;
                    }
                    else if (requestXML.Event == "unsubscribe")
                    {
                        utype = 5;
                    }
                    else
                    {
                        utype = 7;
                    }
                    WX_Business_GroupUserScanEntity userScan = new WX_Business_GroupUserScanEntity(requestXML.MsgType, requestXML.FromUserName, requestXML.Event, requestXML.EventKey, requestXML.Ticket, System.DateTime.Now, weixinid.ToString());
                    try
                    {
                        dimensionBLL demensibll = new dimensionBLL();
                        demensibll.getWX_Business_GroupUserScanUpdate(userScan);
                    }
                    catch (Exception ex)
                    {
                        MyTrace.get().add("添加关注记录出现错误-" + ex.Message);
                    }
                }
            }


            if (requestXML.Event == null)
            {
                StockDoctorPhoneLogBLL.SetStockDoctorPhoneLog(new StockDoctorlogEntity(weixinid, Newsreportid, requestXML.FromUserName, utype, requestXML.ToUserName, requestXML.Content, requestXML.EventKey, stock, result, System.DateTime.Now, requestXML.PicUrl, isstock));
            }
            else
            {
                if (requestXML.Event.ToUpper() != "VIEW") //如果为VIEW在下面Redirect方法中进行记录
                {
                    StockDoctorPhoneLogBLL.SetStockDoctorPhoneLog(new StockDoctorlogEntity(weixinid, Newsreportid, requestXML.FromUserName, utype, requestXML.ToUserName, requestXML.Content, requestXML.EventKey, stock, result, System.DateTime.Now, requestXML.PicUrl, isstock));
                }
            }
            if (result == null || result == "")
            {
                return Content("");
            }
            else
            {
                return Content(result.Replace("{[openid]}", requestXML.FromUserName).Replace("{[weixinId]}", weixinid));
            }
        }

        /// <summary>  
        /// 回复消息(微信信息返回)  
        /// </summary>  
        /// <param name="weixinXML"></param>  
        private string ResponseMsg(RequestXML requestXML)
        {

            try
            {

                if (requestXML.Event == "unsubscribe")
                {
                    return "";
                }
                if (requestXML.Event == "SCAN" || requestXML.Event == "subscribe")  //关注和扫描二维码时
                {
                    return ReturnStrXml(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content, "Welcome"); //回复欢迎语
                }

                #region 签到加的临时判断
                if (weixinid == "8" || weixinid == "13" || weixinid == "14" || weixinid == "15")
                {
                    if (requestXML.Content == "mrqd" || requestXML.EventKey == "mrqd")
                    {
                        ThreadPool.QueueUserWorkItem(new WaitCallback(DailyTaskBLL.AddOneDailyTaskForThread), new DailyTaskEntity()
                        {
                            openid = requestXML.FromUserName,
                            ReportId = -1,
                            TaskType = 1,
                            ydGold =20,
                            weixinId = weixinid
                        });   //添加每日金币任务（放入线程池）
                    }
                }
                #endregion
                string stc = GetXml3(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content, requestXML.EventKey);//菜单点击响应

                if (string.IsNullOrEmpty(stc)) //关键字回复
                {
                    stc = GetKeyCodeReply(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content);
                }

                if (string.IsNullOrEmpty(stc))
                {
                    stc = getKeyWordGPFC(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content, requestXML.EventKey);
                }

                if (string.IsNullOrEmpty(stc))
                {
                    stc = ReturnStrXml(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content);
                }
                return stc;
            }
            catch (NullReferenceException ex)
            {
                MyTrace.get().add("WXOpenController.ResponseMsg.响应发生空对象错误:" + ex.Source + ",TargetSite:" + ex.TargetSite + ",strackTrace" + ex.StackTrace);
                return ReturnStrXml(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content, "Exception");
            }
            catch (Exception ex)
            {
                MyTrace.get().add("WXOpenController.ResponseMsg.响应发生错误:" + ex.Message);
                return ReturnStrXml(requestXML.FromUserName, requestXML.ToUserName, requestXML.Content, "Exception");
            }
        }

        //获取关键字的回复
        public string GetKeyCodeReply(string FromUserName, string ToUserName, string content)
        {
            string retMsg = string.Empty;
            string key = StringTools.ChangeRealKey("keyWordRply", weixinid + content);
            MemcachedTools1 mmtoos = new MemcachedTools1();
            var jsonObj = mmtoos.Get(key);
            if (jsonObj != null)
            {
                KeyWordManagerEntity obj = JsonTools.ToObject<KeyWordManagerEntity>(jsonObj.ToString());
                if (!string.IsNullOrEmpty(obj.replyContent))
                {
                    retMsg = String.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{3}]]></Content><FuncFlag>0</FuncFlag></xml>", FromUserName, ToUserName, StringTools.ConvertDateTimeInt(DateTime.Now), obj.replyContent);
                }
                string key2 = StringTools.ChangeRealKey("keyWordReport", weixinid + content);  //根据微信Id，Content获取缓存数据
                var lst = mmtoos.Get<List<NewsReportEntity>>(key2);
                if (lst != null)
                {
                    if (lst.Count > 0)
                    {

                        if (retMsg == string.Empty) //如果没有文本回复，则回复图文，如果有文本则主动推送图文
                        {
                            StringBuilder sb = new StringBuilder();
                            // StringTools.getNewsPortJsonRep
                            CreateXmlByNewsReportEntity(FromUserName, ToUserName, sb, lst);
                            retMsg = sb.ToString();
                        }
                        else
                        {
                            //ReplyNewsReportsThreads thread = new ReplyNewsReportsThreads(tojson1, strtoken, item.FromUserName, strid, Convert.ToInt32(weixinid), 4);
                            ThreadPara1Entity para = new ThreadPara1Entity() { lstReport = lst, strList = new List<string>() { FromUserName } };
                            ThreadPool.QueueUserWorkItem(new WaitCallback(SendNewsReports), para);
                        }

                    }
                }
                //}`
            }

            return retMsg;

        }

        private void SendNewsReports(Object obj)
        {
            ThreadPara1Entity tp = obj as ThreadPara1Entity;
            string newsRepostIds = string.Empty;
            foreach (var item in tp.lstReport)
            {
                newsRepostIds += item.ID + "^";
            }
            string reportsJson = string.Empty;
            if (tp.lstReport != null && tp.lstReport.Count > 0)
            {
                reportsJson = getNewsPortJson(tp.lstReport);
            }

            if (tp.strtoken == null)  //如果token为空
            {
                var query = ThreadWeiXinBLL.listweixinUser.Where(x => x.id == Convert.ToInt32(weixinid)).ToList();
                if (query != null && query.Count > 0)
                {
                    if (!string.IsNullOrEmpty(query[0].AppId) && !string.IsNullOrEmpty(query[0].AppSecret))
                    {
                        tp.strtoken = TokenHelper.GetToken(query[0].AppId, query[0].AppSecret);
                    }
                }
            }
            string openidStrc = "";
            if (!string.IsNullOrEmpty(tp.strtoken) && !string.IsNullOrEmpty(reportsJson))
            {
                for (int j = 0; j < tp.strList.Count; j++)
                {
                    if (!string.IsNullOrEmpty(tp.strList[j]) && !openidStrc.Contains(tp.strList[j]))
                    {
                        openidStrc += tp.strList[j];
                        string tojson1 = reportsJson.Replace("{0}", tp.strList[j]);
                        tojson1 = tojson1.Replace("{1}", weixinid);
                        weixinResult res = new weixinResult();
                        try
                        {
                            res = JsonTools.ToObject<weixinResult>(TokenHelper.RequestPost(Config.WeiXin_ApiUrl + "message/custom/send?access_token=" + tp.strtoken, tojson1));
                        }
                        catch (Exception ex)
                        {
                            Response.Write(ex.Message);
                            Response.End();
                        }

                        if (res != null)
                        {
                            PropellingLogEntity pplogEntity = new PropellingLogEntity();
                            pplogEntity.id = 0;
                            pplogEntity.newsreportid = newsRepostIds;
                            pplogEntity.weixinid = Convert.ToInt32(weixinid);
                            pplogEntity.ToUsername = tp.strList[j];
                            pplogEntity.errorResult = res.errcode;
                            pplogEntity.updatetime = System.DateTime.Now;
                            pplogEntity.hisid = 3;

                            PropellingLogBLL dalWeixinuser = new PropellingLogBLL();
                            dalWeixinuser.getPropellingUpdate(pplogEntity);

                            // strResult = res.errcode;

                            if (res.errcode == "0")
                            {
                                PropellingLogDAL dal = new PropellingLogDAL();
                                dal.getStockdictor(tp.strList[j], newsRepostIds, weixinid.ToString(), "dtw");
                            }
                        }
                    }
                }
            }
            tp.strList.Clear();
        }


        /// <summary>
        /// 推送json数据拼接
        /// </summary>
        /// <param name="newsr"></param>
        /// <returns></returns>
        public string getNewsPortJson(List<NewsReportEntity> Listnewsr)
        {
            string strContext = "";
            strContext += "{";
            strContext += "\"touser\":\"{0}\",";
            strContext += "\"msgtype\":\"news\",";
            strContext += "\"news\":{";
            strContext += "\"articles\": [";

            for (int i = 0; i < Listnewsr.Count; i++)
            {
                strContext += "{";
                strContext += "\"title\":\"" + Listnewsr[i].title + "\",";
                strContext += "\"description\":\"" + Listnewsr[i].Summary + "\",";
                if (!string.IsNullOrEmpty(Listnewsr[i].OutsideUrl))
                {
                    if (Listnewsr[i].OutsideUrl.Contains("?"))
                    {
                        strContext += "\"url\":\"" + Listnewsr[i].OutsideUrl + "&fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                    }
                    else
                    {
                        strContext += "\"url\":\"" + Listnewsr[i].OutsideUrl + "?fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                    }
                }
                else
                {
                    strContext += "\"url\":\"" + Config.selNewsReportUrl + "?fn={0}&weixinid={1}&id=" + Listnewsr[i].ID + "\",";
                }
                strContext += "\"picurl\":\"" + Listnewsr[i].ImageUrl + "\"";
                strContext += "}";

                if (i != Listnewsr.Count - 1)
                {
                    strContext += ",";
                }
            }
            strContext += "]";
            strContext += "}";
            strContext += "}";
            return strContext;
        }

        public string getKeyWordGPFC(string FromUserName, string ToUserName, string content, string eventkey)
        {
            try
            {
                if (string.IsNullOrEmpty(content))
                {
                    return "";
                }

                if (content.Trim().ToUpper().StartsWith("今日提示") || content.Trim().ToUpper().StartsWith("利好消息") || content.Trim().ToUpper().StartsWith("利好") || content.Trim().ToUpper().StartsWith("利空") || content.Trim().ToUpper().StartsWith("利空消息") || content.Trim().ToUpper().StartsWith("消息") || content.Trim().ToUpper().StartsWith("财富早九点"))
                {
                    WeiXinReplyRule bll = new WeiXinReplyRule();
                    string str = bll.JinRiTiShis(FromUserName, ToUserName);
                    return str;
                }
                else if (content.Trim().ToUpper().Contains("走势"))
                {
                    #region 走势
                    if (content == "走势" || content == "大盘走势" || content == "短期走势" || content == "中期走势")
                    {
                        Vm_Dms_GetnewsbycodeBLL bll = new Vm_Dms_GetnewsbycodeBLL();
                        Vm_Dms_GetnewsbycodeEntity model = new Vm_Dms_GetnewsbycodeEntity();
                        model = bll.GetZouShi();
                        ZDFEntity model2 = new ZDFEntity();
                        string str2 = "";
                        try
                        {
                            model2 = bll.GetZDF();
                            if (model2 != null)
                            {
                                str2 = "6142点至今 大盘:" + model2.FF0 + "%\n";
                                str2 += "1664点至今 大盘:" + model2.FF1 + "%\n";
                                str2 += "近一个月以来 大盘:" + model2.FF3 + "%";
                            }
                        }
                        catch (Exception)
                        {
                            str2 = "——";
                        }

                        if (model != null)
                        {
                            string str = model.F006V_12001 + "\n\n" + model.F013V_12001 + "\n\n";
                            return WeiXinReplyRule.getReply(FromUserName, ToUserName, str + str2);
                        }
                    }
                    else
                    {
                        string secucode = "";
                        secucode = GetCode(content);
                        if (string.IsNullOrEmpty(secucode))
                        {
                            return "";
                        }
                        ZouShiEntity111 list = new ZouShiEntity111();
                        ZouShiBll bll = new ZouShiBll();
                        list = bll.GetList111(secucode);
                        string contents = "";
                        if (list != null)
                        {
                            WeiXinReplyRule wxrbll = new WeiXinReplyRule();
                            Security model = new Security();
                            model = wxrbll.GetAllStocks().FirstOrDefault(x => x.SecuCode == secucode);
                            string xn = model.SecuName + "(" + model.SecuCode + ")";

                            contents = xn + list.Root[0].Top[0].Data[0].Info + "\n\n";
                            contents += "今日走势：" + list.Root[0].Top[0].Data[0].TodayDes + "\n\n";
                            contents += "短期走势：" + list.Root[0].Top[0].Data[0].Techdes + "\n\n";
                            contents += "长期走势：" + list.Root[0].Top[0].Data[0].LongDes + "\n\n";
                            contents += "<a target='_blank' href=\"http://m.emoney.cn/sosoSD/test_pub.html?sc=" + secucode + "&returnf=1\">[点击查看详情]</a>";
                        }
                        return WeiXinReplyRule.getReply(FromUserName, ToUserName, contents);
                    }
                    #endregion
                }
                else
                {
                    WeiXinReplyRule bll = new WeiXinReplyRule();
                    string retMsg = "";
                    string secucode = GetCode(content);
                    if (secucode != null && secucode != "")
                    {
                        isstock = 1;// 说明是股票代码
                        if (weixinid == "8")
                        {
                            retMsg = bll.gotoService(ToUserName, FromUserName, weixinid);
                        }
                        else
                        {
                            retMsg = bll.getGGHF_doctor(secucode, FromUserName, ToUserName);
                        }
                    }
                    else
                    {
                        //接入多客服系统
                        retMsg = bll.gotoService(ToUserName, FromUserName, weixinid);

                    }
                    return retMsg;
                }
            }
            catch (Exception ex)
            {
                MyTrace.get().add("WxOpenController.getKeyWordGPFC发生错误" + ex.Message);
            }
            return "";
        }

        public string GetXml3(string FromUserName, string ToUserName, string content, string eventkey)
        {
            try
            {
                StringBuilder sb = new StringBuilder();
                string strContent = string.IsNullOrEmpty(eventkey) ? (string.IsNullOrEmpty(content) ? "" : content) : eventkey;

                if (!string.IsNullOrEmpty(strContent))
                {
                    MemcachedTools1 mmtoos = new MemcachedTools1();
                    string keys = StringTools.ChangeRealKey("MenuReportMerge", weixinid + strContent); //首先看是否有点击栏目回复多条图文的数据
                    List<NewsReportEntity> newLst = mmtoos.Get<List<NewsReportEntity>>(keys);
                    if (newLst != null)
                    {
                        CreateXmlByNewsReportEntity(FromUserName, ToUserName, sb, newLst);
                    }
                    else
                    {
                        keys = StringTools.ChangeRealKey("newsreport", weixinid + strContent);

                        object objkeys = mmtoos.Get(keys);
                        if (objkeys != null)
                        {
                            var query = JsonTools.ToObject<NewsReportEntity>(objkeys.ToString());
                            Newsreportid = query.ID;
                            if (string.IsNullOrEmpty(query.ImageUrl))//如果不存在图片
                            {
                                return String.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{3}]]></Content><FuncFlag>0</FuncFlag></xml>", FromUserName, ToUserName, StringTools.ConvertDateTimeInt(DateTime.Now), query.Summary);
                            }
                            else
                            {
                                CreateXmlByNewsReportEntity(FromUserName, ToUserName, sb, new List<NewsReportEntity>() { query });
                            }

                        }
                    }
                }
                return sb.ToString();
            }
            catch (Exception)
            {
                return "";
            }
        }

        public string GetCode(string stock)
        {
            GetConentByCodeRule codebll = new GetConentByCodeRule();
            stock = codebll.ContentTozhContent(stock);
            return stock.ToString();
        }

        private void CreateXmlByNewsReportEntity(string FromUserName, string ToUserName, StringBuilder sb, List<NewsReportEntity> query)
        {
            sb.AppendFormat("<xml>");
            sb.AppendFormat("<ToUserName><![CDATA[" + FromUserName + "]]></ToUserName>");
            sb.AppendFormat("<FromUserName><![CDATA[" + ToUserName + "]]></FromUserName>");
            sb.AppendFormat("<CreateTime>" + StringTools.ConvertDateTimeInt(DateTime.Now) + "</CreateTime>");
            sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType>");
            sb.AppendFormat("<ArticleCount>" + query.Count + "</ArticleCount>");
            sb.AppendFormat("<Articles>");
            string ItemTemplate = "<item><Title><![CDATA[{0}]]></Title><Description><![CDATA[{1}]]></Description>"
                                + "<PicUrl><![CDATA[{2}]]></PicUrl><Url><![CDATA[{3}]]></Url></item>";
            for (int i = 0; i < query.Count; i++)
            {
                if (!string.IsNullOrEmpty(query[i].OutsideUrl))
                {
                    sb.AppendFormat(string.Format(ItemTemplate, query[i].title, query[i].Summary, query[i].ImageUrl, query[i].OutsideUrl));
                }
                else
                {
                    sb.AppendFormat(string.Format(ItemTemplate, query[i].title, query[i].Summary, query[i].ImageUrl, Config.selNewsReportUrl + "?fn=" + FromUserName + "&weixinid=" + weixinid + "&id=" + query[i].ID + "&Ntype=" + query[i].MemuType));
                }
            }
            sb.AppendFormat("</Articles>");
            sb.AppendFormat("</xml> ");
        }

        /// <summary>
        /// 返回信息
        /// </summary>
        /// <param name="FromUserName"></param>
        /// <param name="ToUserName"></param>
        /// <param name="content"></param>
        /// <param name="msgType"></param>
        /// <param name="strContent"></param>
        /// <returns></returns>
        public string ReturnStrXml(string FromUserName, string ToUserName, string content, string msgType = "NullTips", string strContent = "")
        {
            string retMsg = "";
            string keys = "";
            switch (msgType)
            {
                case "Welcome":
                    keys = StringTools.ChangeRealKey("reply", weixinid.ToString() + "1");
                    break;
                case "NullTips":
                    keys = StringTools.ChangeRealKey("reply", weixinid.ToString() + "2");
                    break;
                case "gupiao":
                    retMsg = "您好！现在咨询股票的人很多，我们会尽快在24小时内给您答复！感谢你对好股支持，祝您投资顺利！";
                    break;
            }

            if (!string.IsNullOrEmpty(keys))
            {
                MemcachedTools1 mmtoos = new MemcachedTools1();
                var query = mmtoos.Get(keys);
                if (query != null)
                {
                    List<NewsReportEntity> lstnewReport = new List<NewsReportEntity>();
                    var repley = JsonTools.ToObject<ReplyManagerEntity>(query.ToString());
                    if (repley != null)
                    {
                        retMsg = repley.CONTENT;
                    }

                    keys = StringTools.ChangeRealKey("replyReports", repley.id.ToString());
                    var lst = mmtoos.Get<List<NewsReportEntity>>(keys);
                    if (lst != null && lst.Count > 0) //如果存在图文
                    {

                        if (retMsg == string.Empty) //如果没有文本回复，则回复图文，如果有文本则主动推送图文
                        {
                            StringBuilder sb = new StringBuilder();
                            // StringTools.getNewsPortJsonRep
                            CreateXmlByNewsReportEntity(FromUserName, ToUserName, sb, lst);
                            retMsg = sb.ToString();
                            return retMsg;
                        }
                        else
                        {
                            //ReplyNewsReportsThreads thread = new ReplyNewsReportsThreads(tojson1, strtoken, item.FromUserName, strid, Convert.ToInt32(weixinid), 4);
                            ThreadPara1Entity para = new ThreadPara1Entity() { lstReport = lst, strList = new List<string>() { FromUserName } };
                            ThreadPool.QueueUserWorkItem(new WaitCallback(SendNewsReports), para);
                        }
                    }
                }

            }
            return String.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[{3}]]></Content><FuncFlag>0</FuncFlag></xml>", FromUserName, ToUserName, StringTools.ConvertDateTimeInt(DateTime.Now), retMsg);
        }




        /// <summary>
        /// 验证token
        /// </summary>
        private string Valid()
        {
            string echoStr = Request.QueryString["echostr"];
            return echoStr;
            //if (CheckSignature())
            //{
            //    if (!string.IsNullOrEmpty(echoStr))
            //    {
            //        return echoStr;
            //    }
            //}
            //return string.Empty;
        }

        /// <summary>  
        /// 验证微信签名  
        /// </summary>  
        /// * 将token、timestamp、nonce三个参数进行字典序排序  
        /// * 将三个参数字符串拼接成一个字符串进行sha1加密  
        /// * 开发者获得加密后的字符串可与signature对比，标识该请求来源于微信。  
        /// <returns></returns>  
        private bool CheckSignature()
        {
            MemcachedTools1 mmtools = new MemcachedTools1();
            string keys = StringTools.ChangeRealKey("weixinUser", weixinid.ToString());
            var query = mmtools.Get(keys);
            if (query != null)
            {
                weixinUserEntity Bsc = JsonTools.ToObject<weixinUserEntity>(query.ToString());

                string signature = Request.QueryString["signature"];
                string timestamp = Request.QueryString["timestamp"];
                string nonce = Request.QueryString["nonce"];
                string[] ArrTmp = { Bsc.Token, timestamp, nonce };
                Array.Sort(ArrTmp);     //字典排序  
                string tmpStr = string.Join("", ArrTmp);
                tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
                tmpStr = tmpStr.ToLower();
                MyTrace.get().add("tmpStr:" + tmpStr + ",signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce + ",Bsc.Token" + Bsc.Token);
                return (tmpStr == signature ? true : false);

            }
            return true;
        }
        public string strAppid = "";

        public ActionResult NewsReport()
        {
            string guid = Guid.NewGuid().ToString();
            int weixinid = string.IsNullOrEmpty(Request.QueryString["weixinid"]) ? 1 : Convert.ToInt32(Request.QueryString["weixinid"]);
            int newsreportid = string.IsNullOrEmpty(Request.QueryString["id"]) ? 0 : Convert.ToInt32(Request.QueryString["id"]);
            string Ntype = Request.QueryString["Ntype"];
            utype = 2;
            string fromUser = string.IsNullOrEmpty(Request.QueryString["fn"]) ? "" : Request.QueryString["fn"];
            string timestamp = StringTools.ConvertDateTimeInt(System.DateTime.Now).ToString();
            string nonceStr = StringTools.createNonceStr();
            string signature = "";
            string strlinkUrl = "", weixinName = "", clickUrl = "", Author = "", strTitle = "", strdatetime = "", strContent = "", strImage = "", strSummAry = "", contentym = "", contentyj = "", strUserzan = "";
            int newsreportnum = 0;

            if (weixinid > 0 && newsreportid > 0)
            {
                MemcachedTools1 mmtools = new MemcachedTools1();
                string keys = StringTools.ChangeRealKey("weixinUser", weixinid.ToString());
                object objkyes = mmtools.Get(keys);
                if (objkyes != null)
                {
                    weixinUserEntity weixinUser = JsonTools.ToObject<weixinUserEntity>(objkyes.ToString());
                    weixinName = weixinUser.title;
                    clickUrl = weixinUser.gzUrl;
                    Author = weixinUser.Author;
                    strAppid = weixinUser.AppId;
                    string urlsign = Config.Host_Url + Request.RawUrl;
                    string ticket = TokenHelper.GetTicket(weixinUser.AppId, weixinUser.AppSecret);
                    var s = "jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}";
                    s = string.Format(s, ticket, nonceStr, timestamp, urlsign);
                    signature = StringTools.GetShaEntity(s).ToLower();
                }

                strlinkUrl = OAuth2Helper.GetAuthorizeUrl(Config.selNewsReportUrl + "?weixinid=" + weixinid + "&id=" + newsreportid, strAppid);

                keys = StringTools.ChangeRealKey("newsreport", weixinid + newsreportid.ToString());
                objkyes = mmtools.Get(keys);
                NewsReportEntity news;
                if (objkyes == null)
                {
                    lock (lockObject)
                    {
                        news = NewsReportManager.getNewsReportByID(newsreportid);
                        mmtools.Add(keys, JsonTools.ToJson(news), 24 * 365, 0, 0);
                    }
                }
                else
                {
                    news = JsonTools.ToObject<NewsReportEntity>(objkyes.ToString());
                    if (news == null)
                    {
                        lock (lockObject)
                        {
                            news = NewsReportManager.getNewsReportByID(newsreportid);
                            mmtools.Add(keys, JsonTools.ToJson(news), 24 * 365, 0, 0);
                        }
                    }
                }
                if (news != null)
                {

                    strTitle = news.title;
                    strdatetime = news.pubDate.ToString("yyyy-MM-dd");
                    strContent = news.Content;
                    strImage = news.ImageUrl;
                    strSummAry = news.Summary;
                    keys = StringTools.ChangeRealKey("memu", weixinid + news.MemuType);
                    MenuEntity objmemuEntity = mmtools.Get<MenuEntity>(keys);
                    if (objmemuEntity != null)
                    {
                        contentym = objmemuEntity.contentym;
                        contentyj = objmemuEntity.contentyj;
                    }
                    keys = StringTools.ChangeRealKey("newsreportkey", weixinid.ToString() + news.ID.ToString()); //获取和并修改newsreports的阅读次数
                    object objnum = mmtools.Get(keys);
                    if (objnum != null)
                    {
                        newsreportnum = Convert.ToInt32(objnum.ToString()) + 1;
                    }
                    else
                    {
                        newsreportnum = 5000;
                    }
                    mmtools.Add(keys, newsreportnum, 24 * 365, 0, 0);


                    keys = StringTools.ChangeRealKey("zannum", news.ID.ToString());
                    object objnums = mmtools.Get(keys);
                    if (objnums != null)
                    {
                        strUserzan = "<img src=\"" + StringTools.GetStaticFile("Static/Image/zan2.png") + "\" style=\"height: 13px;\" />&nbsp;" + objnums;
                    }
                    else
                    {
                        strUserzan = "<img src=\"" + StringTools.GetStaticFile("Static/Image/zan1.png") + "\" style=\"height: 13px;\" />&nbsp;" + baseZanNum;
                    }
                }
            }

            ViewBag.guid = guid;
            ViewBag.weixinid = weixinid;
            ViewBag.newsreportid = newsreportid;
            ViewBag.Ntype = Ntype;
            ViewBag.fromUser = fromUser;
            ViewBag.timestamp = timestamp;
            ViewBag.nonceStr = nonceStr;
            ViewBag.signature = signature;
            ViewBag.newsreportnum = newsreportnum;
            ViewBag.strAppid = strAppid;

            ViewBag.strlinkUrl = strlinkUrl;
            ViewBag.weixinName = weixinName;
            ViewBag.clickUrl = clickUrl;
            ViewBag.Author = Author;
            ViewBag.strTitle = strTitle;

            ViewBag.strdatetime = strdatetime;
            ViewBag.strContent = strContent.Replace("{[openid]}", fromUser);
            ViewBag.strImage = strImage;
            ViewBag.strSummAry = strSummAry;
            ViewBag.contentym = contentym;
            ViewBag.contentyj = contentyj;
            ViewBag.strUserzan = strUserzan;

            StockDoctorPhoneLogBLL.SetStockDoctorPhoneLog(new StockDoctorlogEntity(weixinid.ToString(), newsreportid, fromUser, utype, "", "", "", stock, result, System.DateTime.Now, "", isstock));
            if (weixinid == 8 || weixinid == 13 || weixinid == 14 || weixinid == 15)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(DailyTaskBLL.AddOneDailyTaskForThread), new DailyTaskEntity()
                {
                    openid = fromUser,
                    ReportId = newsreportid,
                    TaskType = 3,
                    ydGold = 30,
                    weixinId = weixinid.ToString()
                });   //添加每日金币任务（放入线程池）
            }
            return View();
        }

        public string getSignature(string nonceStr, string timestamp, string weixinid)
        {
            string urlsign = Config.Host_Url + Request.RawUrl;
            string str = "";
            MemcachedTools1 mmtools = new MemcachedTools1();
            string keys = StringTools.ChangeRealKey("weixinUser", weixinid.ToString());
            weixinUserEntity objwexinuser = mmtools.Get<weixinUserEntity>(keys);
            if (objwexinuser != null)
            {
                if (!string.IsNullOrEmpty(objwexinuser.AppId))
                {
                    strAppid = objwexinuser.AppId;
                    string ticket = TokenHelper.GetTicket(objwexinuser.AppId, objwexinuser.AppSecret);
                    var s = "jsapi_ticket={0}&noncestr={1}&timestamp={2}&url={3}";
                    s = string.Format(s, ticket, nonceStr, timestamp, urlsign);
                    str = StringTools.GetShaEntity(s).ToLower();
                }
            }
            return str;
        }

        public string ZanUser()
        {
            //  string strResult = "18";
            string fn = Request.QueryString["fn"];
            string newsid = Request.QueryString["newsid"];

            MemcachedTools1 mmtools = new MemcachedTools1();
            string keys = StringTools.ChangeRealKey("zanuser", fn + newsid);
            object objkeys = mmtools.Get(keys);
            if (objkeys != null)  //如果有缓存
            {
                mmtools.Remove(keys);
                keys = StringTools.ChangeRealKey("zannum", newsid);
                object objnums = mmtools.Get(keys);
                if (objnums != null)
                {
                    mmtools.Add(keys, Convert.ToInt32(objnums) - 1, 24 * 365, 0, 0);
                    baseZanNum = Convert.ToInt32(objnums) - 1;
                }
                else
                {
                    mmtools.Add(keys, 18, 24 * 365, 0, 0);
                }
            }
            else
            {
                mmtools.Add(keys, 18, 24 * 365, 0, 0);
                keys = StringTools.ChangeRealKey("zannum", newsid);
                object objnums = mmtools.Get(keys);
                if (objnums != null)
                {
                    // strResult = (Convert.ToInt32(objnums) + 1).ToString();
                    baseZanNum = Convert.ToInt32(objnums) + 1;
                    mmtools.Add(keys, Convert.ToInt32(objnums) + 1, 24 * 365, 0, 0);
                    //GroupUserBLL bll = new GroupUserBLL();
                    // bll.dianzanDal(fn, newsid, "1");
                }
                else
                {
                    baseZanNum = 19;
                    mmtools.Add(keys, 19, 24 * 365, 0, 0);

                    // GroupUserBLL bll = new GroupUserBLL();
                    // bll.dianzanDal(fn, newsid, "1");
                }
            }
            return baseZanNum.ToString();
        }

        public void getISStock(string content, string eventkey)
        {
            if (string.IsNullOrEmpty(content) && string.IsNullOrEmpty(eventkey))
            {
                isstock = 0;
            }
            else
            {
                if (content.Trim() == "次新股" || content.Trim() == "新能源" || content.Trim() == "龙虎" || content.Trim() == "龙虎榜")
                {
                    isstock = 0;
                }
                else
                {
                    string strContent = "";
                    if (!string.IsNullOrEmpty(content))
                    {
                        strContent = content;
                    }
                    if (!string.IsNullOrEmpty(eventkey))
                    {
                        strContent = eventkey;
                    }
                    string keys = "";
                    MemcachedTools1 mmtoos = new MemcachedTools1();
                    string strCon = StringTools.GetNumberTostr(strContent);
                    List<StockALLEntity> listStockAll = new List<StockALLEntity>();
                    if (strCon != "" && strCon.Length > 3 && strCon.Length < 7)
                    {
                        keys = StringTools.ChangeRealKey("ListStockAll", "");
                        var query = mmtoos.Get(keys);
                        if (query != null)
                        {
                            listStockAll = JsonTools.ToObject<List<StockALLEntity>>(query.ToString());
                            if (listStockAll != null && listStockAll.Count > 0)
                            {
                                var queryList = listStockAll.Where(x => x.ID.Contains(strCon)).ToList();
                                if (queryList != null && queryList.Count > 0)
                                {
                                    isstock = 1;
                                    queryList.Clear();
                                }
                            }
                            query = null;
                        }
                        strCon = strCon.Replace(".", "");
                        strCon = Convert.ToInt32(strCon).ToString("000000");
                        keys = StringTools.ChangeRealKey("ListStockAllcode", "");
                        query = mmtoos.Get(keys);
                        if (query != null)
                        {
                            Regex reg = new Regex(query.ToString());
                            string strCon1 = reg.Replace(strCon, StringTools.CapCode);
                            if (strCon1 != strCon)
                            {
                                isstock = 1;
                            }
                        }
                    }

                    if (isstock == 0)
                    {
                        strCon = Regex.Replace(strContent, @"[^\u4e00-\u9fa5]", "");
                        if (strCon != "" && strCon.Length >= 3 && strCon.Length <= 5)
                        {
                            strCon = StringTools.GetChineseSpell(strCon);
                            if (strCon.Contains("*"))
                            {
                                strCon = strCon.Replace("*", "");
                            }

                            if (listStockAll == null || listStockAll.Count < 1)
                            {
                                keys = StringTools.ChangeRealKey("ListStockAll", "");
                                var query = mmtoos.Get(keys);
                                if (query != null)
                                {
                                    listStockAll = JsonTools.ToObject<List<StockALLEntity>>(query.ToString());
                                }
                            }

                            if (listStockAll != null && listStockAll.Count > 0)
                            {
                                var queryList = listStockAll.Where(x => x.Abbr.Contains(strCon)).ToList();
                                if (queryList != null && queryList.Count > 0)
                                {
                                    isstock = 1;
                                    queryList.Clear();
                                }
                            }
                        }
                    }
                    listStockAll.Clear();
                }
            }
        }

        public ActionResult Redirect()
        {

            try
            {
                string keyCode = Request["keyCode"] == null ? "" : Request["keyCode"];
                string goUrl = HttpUtility.UrlDecode(Request["goUrl"]);
                string weiXinId = Request["weixinId"];
                string appId = string.Empty;
                string secret = string.Empty;
                if (weiXinId != null)
                {
                    weixinUserBLL weixinuserBll = new weixinUserBLL();
                    weixinUserEntity info = weixinuserBll.GetWeixinUserFromCache(weiXinId);
                    appId = info.AppId;
                    secret = info.AppSecret;
                }
                string code = Request["code"];
                string posrUrl = Config.WeiXin_access_tokenApiUrl + string.Format("?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code);
                string jsonResult = NetHelper.LoadData(posrUrl, null);
                MyTrace.get().add("WXOpenController.Redirect.jsonResult:" + jsonResult + ",weixinId=" + weiXinId + ",code:" + code);
                JsonModelEntity jm = JsonTools.ToObject<JsonModelEntity>(jsonResult);
                StockDoctorPhoneLogBLL.SetStockDoctorPhoneLog(new StockDoctorlogEntity(weiXinId, 0, jm.openid, 1, "", "", keyCode, stock, result, System.DateTime.Now, "", isstock));
                if (!string.IsNullOrEmpty(goUrl))
                {
                    if (goUrl.Contains("?"))
                    {
                        goUrl += "&openid=" + jm.openid;
                    }
                    else
                    {
                        goUrl += "?openid=" + jm.openid;
                    }
                }
                goUrl += "&access_token=" + jm.access_token;
                MyTrace.get().add("WXOpenController.Redirect.acces_token:" + jm.access_token + ",openId:" + jm.openid + " code:" + code + "");
                Response.Redirect(goUrl);
            }
            catch (Exception)
            {
                return Content("鉴权发生错误，请重试！");
            }
            return Content("鉴权发生错误!，请重试！");
        }

        /// <summary>
        /// 用于活动
        /// </summary>
        /// <returns></returns>
        public ActionResult Redirect2()
        {
            try
            {
                string keyCode = Request["keyCode"] == null ? "" : Request["keyCode"];
                string goUrl = HttpUtility.UrlDecode(Request["goUrl"]);
                string weiXinId = Request["weixinId"];
                string appId = string.Empty;
                string secret = string.Empty;
                if (weiXinId != null)
                {
                    weixinUserBLL weixinuserBll = new weixinUserBLL();
                    weixinUserEntity info = weixinuserBll.GetWeixinUserFromCache(weiXinId);
                    appId = info.AppId;
                    secret = info.AppSecret;
                }
                string code = Request["code"];
                string posrUrl = Config.WeiXin_access_tokenApiUrl + string.Format("?appid={0}&secret={1}&code={2}&grant_type=authorization_code", appId, secret, code);
                string jsonResult = NetHelper.LoadData(posrUrl, null);
                MyTrace.get().add("WXOpenController.Redirect.jsonResult:" + jsonResult + ",weixinId=" + weiXinId + ",code:" + code);
                JsonModelEntity jm = JsonTools.ToObject<JsonModelEntity>(jsonResult);
                StockDoctorPhoneLogBLL.SetStockDoctorPhoneLog(new StockDoctorlogEntity(weiXinId, 0, jm.openid, 1, "", "", keyCode, stock, result, System.DateTime.Now, "", isstock));
                if (!string.IsNullOrEmpty(goUrl))
                {
                    if (goUrl.Contains("?"))
                    {
                        goUrl += "&openid=" + jm.openid;
                    }
                    else
                    {
                        goUrl += "?openid=" + jm.openid;
                    }
                }
                goUrl += "&access_token=" + jm.access_token;
                MyTrace.get().add("WXOpenController.Redirect.acces_token:" + jm.access_token + ",openId:" + jm.openid + " code:" + code + "");
                Response.Redirect(goUrl);
            }
            catch (Exception)
            {
                return Content("鉴权发生错误，请重试！");
            }
            return Content("鉴权发生错误!，请重试！");
        }





    }




}
